<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <script src="/assets/js/def.js"></script>
    <link rel="stylesheet" href="/assets/lib/bootstrap/css/bootstrap.min.css" />
    <script src="/assets/lib/bootstrap/js/bootstrap.min.js"></script>
    <script src="bs.beamDialog.js"></script>
    <style type="text/css">
      .menu-title-td {
        min-width: 300px;
      }
      .menu-type-td {
        min-width: 100px;
      }
      .menu-operate-td {
        min-width: 120px;
      }
      .menu-title {
        margin-left: 10px;
      }
      .menu-title label {
        margin-right: 10px;
      }
      .sub-menu-group .menu-title {
        margin-left: 40px;
      }
      td {
        word-break: break-all;
      }
    </style>
  </head>
  <body>
    
    <!-- 当前已有菜单 -->
    <!-- 菜单 buttons 结构树 -->
    <form id="mainForm">
      <table class="table" id='menu-list'>
        <thead>
          <tr>
            <th class="menu-title-td">菜单名称</th>
            <th class="menu-type-td">菜单类型</th>
            <th>菜单链接/菜单事件</th>
            <th class="menu-operate-td">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr class="main-menu">
            <td><span class="caret"></span><span class="menu-title">即刻出发</span></td>
            <td>view</td>
            <td>http://service.kuaibuss.com/weixin/index.html</td>
            <td class="menu-operate"></td>
          </tr>
        </tbody>
        <tbody>
          <tr class="main-menu">
            <td><span class="caret"></span><span class="menu-title">关于线路</span></td>
            <td></td>
            <td></td>
            <td class="menu-operate"></td>
          </tr>
        </tbody>
        <tbody class="sub-menu-group">
          <tr class="sub-menu">
            <td><span class="menu-title">已开通线路</span></td>
            <td>view</td>
            <td>http://mp.weixin.qq.com/s?__biz=MzA5MTExNjM1Mg==&amp;mid=208349831&amp;idx=1&amp;sn=cd1aadda50d4d2b580a881dbe9431d07&amp;scene=0&amp;key=dffc561732c22651fefdb88f1657d1b11ffb50cdc79d852ae229c64aba89101aac7bab1b3817c1a9c02a7dabae3d1f77&amp;ascene=0&amp;uin=OTMwMjQyMjAw&amp;devicetype=iMac+MacBookPro11%2C1+OSX+OSX+10.10.5+build(14F27)&amp;version=11020201&amp;pass_ticket=SXBVrp%2FzS42Lpv4JvY3UHq990EcwXJKiytZdJs92FzFq474fMDqAZN0S9%2FuwUsiK</td>
            <td class="menu-operate"></td>
          </tr>
          <tr class="sub-menu">
            <td><span class="menu-title">线路征集令</span></td>
            <td>view</td>
            <td>http://www.sojump.com/jq/5587272.aspx</td>
            <td class="menu-operate"></td>
          </tr>
        </tbody>
        <tbody>
          <tr class="main-menu">
            <td><span class="caret"></span><span class="menu-title">我的UBUS</span></td>
            <td></td>
            <td></td>
            <td class="menu-operate"></td>
          </tr>
        </tbody>
        <tbody class="sub-menu-group">
          <tr class='sub-menu'>
            <td><span class="menu-title">如何乘车</span></td>
            <td>view</td>
            <td>http://mp.weixin.qq.com/s?__biz=MzA5MTExNjM1Mg==&amp;mid=207913797&amp;idx=1&amp;sn=bcd55074406728147f1dce3f0434bb57&amp;scene=0&amp;key=dffc561732c2265124ce3c91f394614b2ac8d16e27cd7222630b18e09b33aec85160e0c9ff2c719d4e8db954fa575752&amp;ascene=0&amp;uin=OTMwMjQyMjAw&amp;devicetype=iMac+MacBookPro11%2C1+OSX+OSX+10.10.5+build(14F27)&amp;version=11020113&amp;pass_ticket=2OoYMw45tYHGG7mQUZdbw28jRa053XHMhBbd9nbUk6NPZO6gsKr5vwpiZfo5e5m3</td>
            <td class="menu-operate"></td>
          </tr>
          <tr class='sub-menu'>
            <td><span class="menu-title">常见问题</span></td>
            <td>view</td>
            <td>http://mp.weixin.qq.com/s?__biz=MzA5MTExNjM1Mg==&amp;mid=207908020&amp;idx=1&amp;sn=c048b5d2e0ddc582654a3b44886accaa&amp;scene=0&amp;key=dffc561732c226515c0c0aa7d5a8f54f1e41a5d59c178ff146d48536624245faab325a102f14b139b4b1876b37d7f179&amp;ascene=0&amp;uin=OTMwMjQyMjAw&amp;devicetype=iMac+MacBookPro11%2C1+OSX+OSX+10.10.5+build(14F27)&amp;version=11020113&amp;pass_ticket=2OoYMw45tYHGG7mQUZdbw28jRa053XHMhBbd9nbUk6NPZO6gsKr5vwpiZfo5e5m3</td>
            <td class="menu-operate"></td>
          </tr>
          <tr class='sub-menu'>
            <td><span class="menu-title">联系客服</span></td>
            <td>view</td>
            <td>http://mp.weixin.qq.com/s?__biz=MzA5MTExNjM1Mg==&amp;mid=207916768&amp;idx=1&amp;sn=3a0a54e5c15028f5f6c2f7b6a64b5fe7&amp;scene=0&amp;key=dffc561732c22651f8470aa5ca9023e3c577f1c742249085d4484907b91d1905a45afa9770933051cfe76cc06d0d89f9&amp;ascene=0&amp;uin=OTMwMjQyMjAw&amp;devicetype=iMac+MacBookPro11%2C1+OSX+OSX+10.10.5+build(14F27)&amp;version=11020113&amp;pass_ticket=2OoYMw45tYHGG7mQUZdbw28jRa053XHMhBbd9nbUk6NPZO6gsKr5vwpiZfo5e5m3</td>
            <td class="menu-operate"></td>
          </tr>
        </tbody>
      </table>
    </form>

    <script type="text/javascript">
    (function() {
      var init = function($elem) {
        newAddMainMenuButton($elem);
        $('.main-menu').each(function(i) {
          newEditMenuButton($(this), i);
          newAddSubMenuButton($(this), i);
        });
      };

      /**
       * [newAddMainMenuButton description]
       * @param  {[type]} $elem [table]
       * @return {[type]}       [description]
       */
      var newAddMainMenuButton = function($elem) {
        var $target = $('<tbody>');
        var $button = createTableTr(
          $('<div class="menu-title">').append(
            $('<button type="button" class="btn btn-default btn-sm">添加主菜单</button>').click(function() {
                newAddMainMenuForm($button);
            })
          ).append(
            $('<button type="button" class="btn btn-primary btn-sm">确定</button>').click(function() {
              submitRequest('add');
            })
          )
        );
        $elem.append($target);
        $target.append($button);
      }

      var newAddMainMenuForm = function($baseElem) {
        var mainIdx = $('.main-menu').length
        var mainButtonName = 'buttons[' + mainIdx + ']';
        var $mainMenu = genRowForm(mainButtonName).addClass('main-menu');
        $baseElem.parent().before($('<tbody>').append($mainMenu));
        newAddSubMenuButton($mainMenu, mainIdx);
      }

      var newEditMenuButton = function($elem, mainIdx, subIdx) {
        var $menuOperate = $elem.children('.menu-operate');

        $menuOperate.html('').append(
          $('<button type="button" class="btn btn-default btn-sm">编辑</button>').one('click', function() {
            newEditMenuForm($elem, mainIdx, subIdx);
          })
        ).append(
          $('<button type="button" class="btn btn-danger btn-sm">删除</button>').on('click', function() {
            deleteMenu($elem, mainIdx, subIdx);
          })
        );
      };

      var newEditMenuForm = function($elem, mainIdx, subIdx) {
        var buttonName = 'buttons[' + mainIdx + ']';
        if (subIdx != undefined)
          buttonName += '.subButtons[' + subIdx + ']';
        var $editMenuForm = genRowForm(buttonName).addClass('edit-menu')
          .append($('<td>').append($('<button type="button" class="btn btn-primary btn-sm">确定</button>').one('click', function() {
              submitRequest('edit');
            })).append($('<button type="button" class="btn btn-default btn-sm">取消</button>').one('click', function() {
              $editMenuForm.after($elem);
              $editMenuForm.remove();
              newEditMenuButton($elem, mainIdx, subIdx);
            })));
        var $menuTds = $elem.children('td');
        $editMenuForm.find('input[name="' + buttonName + '.name"]').val($menuTds.eq(0).text());
        $editMenuForm.find('select[name="' + buttonName + '.type"]').val($menuTds.eq(1).text());
        //default is a .url input
        if ($menuTds.eq(1).text() == 'click')
        {
          $editMenuForm.find('input[name="' + buttonName + '.url"]')
            .attr('name', buttonName + ".key")
            .attr('placeholder', '填写事件KEY值, 如 V1001_TODAY_NEWS').val($menuTds.eq(2).text());
        }
        else
        {
          $editMenuForm.find('input[name="' + buttonName + '.url"]').val($menuTds.eq(2).text());
        }
        $elem.after($editMenuForm);
        $elem.remove();
      };

      var deleteMenu = function($elem, mainIdx, subIdx) {
        confirm('确认删除？',function() {
          return;
          $("#mainForm").append($('<input name="' + subButtonName + '.name'))
        });
      };
      
      var newAddSubMenuButton = function($elem, mainIdx) {
        //添加子菜单按钮
        var $subMenuGroup;
        if ($elem.parent().next().is('.sub-menu-group'))
        {
          $subMenuGroup = $elem.parent().next();
        }
        else
        {
          $subMenuGroup = $('<tbody class="sub-menu-group">');
          $elem.parent().after($subMenuGroup);
        }
        var $button = createTableTr(
            $('<div class="menu-title">').append(
              $('<button type="button" class="btn btn-default btn-sm">添加子菜单</button>').click(function() {
                newAddSubMenuForm($button, mainIdx);
              })
            ).append(
              $('<button type="button" class="btn btn-primary btn-sm">确定</button>').click(function() {
                submitRequest('add');
              })
            )
          );
        $subMenuGroup.append($button);

        //子菜单编辑按钮
        $subMenuGroup.children('.sub-menu').each(function(i) {
          newEditMenuButton($(this), mainIdx, i);
        });
      };

      /**
       * [newAddSubMenuForm description]
       * @param  {[type]} $baseElem [button $dom]
       * @param  {[type]} mainIdx   [description]
       * @return {[type]}           [description]
       */
      var newAddSubMenuForm = function($baseElem, mainIdx) {
        var subIdx = $baseElem.parent().children('.sub-menu').length;
        var subButtonName = 'buttons[' + mainIdx + '].subButtons[' + subIdx + ']';
        $baseElem.before(genRowForm(subButtonName).addClass('sub-menu'));
      };

      var submitRequest = function(operate) {
        $("#mainForm").prop("action", "/test/" + operate);
        $("#mainForm").prop("method", "post");
        $("#mainForm").submit();
      }

      var createTableTr = function() {
        var $elem = $('<tr>');
        for (var i = 0; i < arguments.length; i++)
        {
          $elem.append($('<td>').append(arguments[i]));
        }
        return $elem;
      };

      var genRowForm = function(prefButtonName) {
        var isSubMenu = prefButtonName.indexOf('subButtons') != -1;
        return createTableTr(
          isSubMenu ?
          $('<div class="menu-title"><input class="form-control" name="' + prefButtonName +'.name"></div>')
          : $('<div class="form-inline"><div class="form-group menu-title"><label><span class="caret"></span></label><input class="form-control" name="' + prefButtonName +'.name"></div></div>'),
          $('<select class="form-control" name="' + prefButtonName +'.type">')
            .append($('<option value="view">view</option>')
              .click(function() {
                $("input[name='" + prefButtonName + ".key']").attr('name', prefButtonName + ".url")
                  .attr('placeholder', '填写链接地址, 如 http://www.kuaibuss.com').val('');
              })
            ).append($('<option value="click">click</option>')
              .click(function() {
                $("input[name='" + prefButtonName + ".url']").attr('name', prefButtonName + ".key")
                  .attr('placeholder', '填写事件KEY值, 如 V1001_TODAY_NEWS').val('');
              })
            ),
          $('<input class="form-control" name="' + prefButtonName +'.url">').attr('placeholder', '填写链接地址, 如 http://www.kuaibuss.com')
        );
      };

      function confirm(message, callback) {
        $.beamDialog({
          title: '系统提示',
          content: message,
          showCloseButton: true,
          otherButtons:["确定"],
          otherButtonStyles: ['btn-danger'],
          bsModalOption: {keyboard: true},
          clickButton:function(sender, modal, index) {
            callback();
            $(this).closeDialog(modal);
          }
        });
      }
      
      init($('#menu-list'));
    }());
    </script>
  </body>
</html>